# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
# # @Copyright © 启明星辰 版权所有
# # @Time    : 2024/4/26 15:54
# # @Author  : 胡浩浩
# # @File    : jmespath_express.py
# # @IDE     : PyCharm
# # @description :
# from contextlib import asynccontextmanager
#
# import requests
# import uvicorn
# import asyncio
# import httpx
# from fastapi import FastAPI
#
# TARGET_URL = "http://192.168.114.37:7777/"
#
#
# async def periodic_task():
#     while True:
#         async with httpx.AsyncClient() as client:
#             print("我是定时任务")
#             response = await client.get(TARGET_URL)
#             # 处理响应
#             print(response.text)
#             print(f"Fetched {TARGET_URL}: {response.status_code}")
#         await asyncio.sleep(60)  # 每10秒轮询一次
#
# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     # 在此处启动后台任务
#     task = asyncio.create_task(periodic_task())
#     try:
#         yield
#     finally:
#         # 确保应用关闭时结束任务
#         task.cancel()
#         await task
#
# app = FastAPI(lifespan=lifespan)
#
#
# @app.get("/")
# async def read_root():
#     return {"message": "Hello World"}

import asyncio
import time

import httpx
import uvicorn
from fastapi import FastAPI
from apscheduler.schedulers.asyncio import AsyncIOScheduler

app = FastAPI()
# 创建调度器
scheduler = AsyncIOScheduler()


async def fetch_baidu_api():
    async with httpx.AsyncClient() as client:
        response = await client.get("http://192.168.114.37:7777/check")
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')}",response.text)
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')}Fetched {len(response.text)} characters from http://192.168.114.37:7777/check")


@app.on_event("startup")
async def startup_event():
    # 添加定时任务，每隔1分钟运行一次
    scheduler.add_job(fetch_baidu_api, "interval", minutes=1)
    scheduler.start()
    print("Scheduler started")


@app.on_event("shutdown")
async def shutdown_event():
    # 停止调度器
    scheduler.shutdown()
    print("Scheduler stopped")


if __name__ == '__main__':
    uvicorn.run(app, port=7777, host="192.168.114.124")
